package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.YddAdvposDto;
import com.itheima.ydd.entity.YddAdvimg;
import com.itheima.ydd.entity.YddAdvpos;
import com.itheima.ydd.mapper.YddAdvposMapper;
import com.itheima.ydd.service.YddAdvimgService;
import com.itheima.ydd.service.YddAdvposService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 广告位业务层接口实现类
 */
@Service
public class YddAdvposServiceImpl extends ServiceImpl<YddAdvposMapper, YddAdvpos> implements YddAdvposService {

    @Autowired
    private YddAdvimgService yddAdvimgService;


    /**
     * 广告分页条件查询
     * @param page 页码
     * @param limit 页面条目数
     * @param yddAdvpos 查询条件,广告名,广告描述
     * @return 分页查询对象
     */
    @Override
    public PageResult getList(Long page, Long limit, YddAdvpos yddAdvpos){
        //创建分页查询对象,传入查询条件
        Page<YddAdvpos> pageInfo=new Page<>(page,limit);
        LambdaQueryWrapper<YddAdvpos> lqw=new LambdaQueryWrapper<>();
        lqw.like(yddAdvpos.getAdvposname()!=null,YddAdvpos::getAdvposname,yddAdvpos.getAdvposname())
                .like(yddAdvpos.getAdvposdesc()!=null,YddAdvpos::getAdvposdesc,yddAdvpos.getAdvposdesc());
        //查询广告位表,获取查询结果
        this.page(pageInfo,lqw);
        //查询广告位下的图片数,并返回到dto中
         List<YddAdvposDto> dtoList=pageInfo.getRecords().stream().map(advpos->{
            YddAdvposDto dto=new YddAdvposDto();
            BeanUtils.copyProperties(advpos,dto);
            //查询该广告位下的广告图数量
            LambdaQueryWrapper<YddAdvimg> qw=new LambdaQueryWrapper<>();
            qw.eq(YddAdvimg::getAdvimgpos,advpos.getId());
            int advposnum = yddAdvimgService.count(qw);
            //设置广告位的图片数量并返回
            dto.setAdvposnum(advposnum);
            return dto;
        }).collect(Collectors.toList());

        //返回数据
        return PageResult.init(pageInfo.getTotal(), limit, page, dtoList);
    }

    @Override
    public ResultData deleteById(Long id) {
        if(id==null)  throw new BusinessException("数据不存在");
        //查询该广告位下是否有图片
        LambdaQueryWrapper<YddAdvimg> lqw=new LambdaQueryWrapper<>();
        lqw.eq(YddAdvimg::getAdvimgpos,id);
        List<YddAdvimg> list = yddAdvimgService.list(lqw);
        if(list==null || list.size()==0) {
            //不存在图片.进行删除
            if(this.removeById(id)) return ResultData.ok("","删除成功");
            return ResultData.error("删除失败");
        }
        return ResultData.error("该广告位下有广告图,无法删除");
    }

}
